/********************************************
* Copyrigt (C) rumi
* Module: drv_ws2812.c
*********************************************/
#include "drv_ws2812.h"

// static const char *TAG = "drv_ws2812.c";
/**************************Init Area*********************************/
PinConfig_DrvDef Pin_WS2812 = {
  .PinNum = GPIO_NUM_48,
};

WS2812Dev_DrvDef Dev_WS2812 = {
    .color = {0,0,0},
    .pin = &Pin_WS2812,
};

static void Drv_Delay_1_5us(){
    static uint8_t delay;
    for(uint8_t t = 0;t<16;t++){delay++;}
}

/*******************************************************************/
// high 400ns  low 800ns  is ok
static void Drv_WS2812_SendHigh(WS2812Dev_DrvDef *device)
{
    Drv_IO_Control(device->pin,E_PIN_WRITE,high);
    // 0.5us
    Drv_IO_Control(device->pin,E_PIN_WRITE,low);
    Drv_Delay_1_5us(); //1.5us+0.5us
}

// high 800ns  low 400ns  is ok
static void Drv_WS2812_SendLow(WS2812Dev_DrvDef *device)
{
    Drv_IO_Control(device->pin,E_PIN_WRITE,high);
    Drv_Delay_1_5us(); //1.5us+0.5us
    Drv_IO_Control(device->pin,E_PIN_WRITE,low);
    // 0.5us
}


// static void Drv_WS2812_SendReset(WS2812Dev_DrvDef *device)
// {
//     Drv_IO_Control(device->pin,E_PIN_WRITE,low);
//     Drv_Delay_100ns(60);
//     Drv_IO_Control(device->pin,E_PIN_WRITE,high);
//     Drv_IO_Control(device->pin,E_PIN_WRITE,low);
// }

static void Drv_WS2812_SendRGB(WS2812Dev_DrvDef *device)   
{
    uint8_t i;
    unsigned char lucbyte;
    WS2812_ColorData RGB_Data;
    uint32_t lRGB_Data;
    RGB_Data.R = device->color.R;
    RGB_Data.G = device->color.G;
    RGB_Data.B = device->color.B;
    lRGB_Data = ((uint32_t)RGB_Data.B)*256*256+((uint32_t)RGB_Data.R)*256+((uint32_t)RGB_Data.G);
    Bsp_WS2812_TX_Color(&lRGB_Data);
    // for(i = 24; i > 0; i--)
    // {
    //     lucbyte = ((lRGB_Data >>i) & 0x01);  
    //     if(lucbyte == 1)
    //     {
    //         Drv_WS2812_SendHigh(device);
    //     }
    //     else
    //     {
    //         Drv_WS2812_SendLow(device);
    //     }
    // }
}

uint8_t Drv_WS2812_Control(WS2812Dev_DrvDef *device,uint8_t type,void *pbuffer)
{
  switch((WS2812_CTRL_EnumDef)type)
  {
    case E_WS2812_SET:
    {
      Drv_WS2812_SendRGB(device);
      break;
    }
    default:
      break;
  }
  return 1;
}

/********************************************
 * End of file
*********************************************/
